from tools_algorithm import *


class Solution:
    def countPairs(self, nums: List[int]) -> int:
        cnt = Counter()
        1000000
        b = [1]
        for i in range(5):
            b.append(b[-1] * 10)
        ans = 0

        def swap(num, i, j):
            i, j = b[i], b[j]
            ni = num // i % 10
            nj = num // j % 10
            ans = num - ni * i - nj * j
            ans = ans + ni * j + nj * i
            return ans

        for num in nums:
            ans += cnt[num]
            for i in range(6):
                for j in range(i + 1, 6):
                    em = swap(num, i, j)
                    if em != num:
                        ans += cnt[em]
            cnt[num] += 1
        return ans
